import { PlusOutlined } from '@ant-design/icons';
import { Tree } from 'antd';
import React, { useState } from 'react';
import styles from './../index.css';

interface OrgTreeProps {
  treeData: any[];
  selectedKey: string;
  expandedKeys: string[];
  autoExpandParent: boolean;
  onSelect: (keys: React.Key[]) => void;
  onExpand: (keys: React.Key[]) => void;
  onAddClick?: (node: any) => void;
}

const OrgTree: React.FC<OrgTreeProps> = ({
  treeData,
  selectedKey,
  expandedKeys,
  autoExpandParent,
  onSelect,
  onExpand,
  onAddClick,
}) => {
  // 存储当前悬浮的节点ID
  const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null);

  // 自定义节点渲染
  const renderTreeNode = (nodeData: any) => {
    return (
      <div
        className={styles['custom-tree-node']}
        onMouseEnter={() => setHoveredNodeId(nodeData.key)}
        onMouseLeave={() => setHoveredNodeId(null)}
      >
        <span>{nodeData.title}</span>
        {hoveredNodeId === nodeData.key && onAddClick && (
          <PlusOutlined
            className={styles['add-icon']}
            onClick={(e) => {
              e.stopPropagation(); // 只在点击加号时阻止冒泡
              onAddClick(nodeData);
            }}
          />
        )}
      </div>
    );
  };
  return (
    <div className={styles.orgTree}>
      <Tree
        treeData={treeData}
        selectedKeys={[selectedKey]}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onSelect={onSelect}
        onExpand={onExpand}
        className={styles['custom-tree']}
        showLine={{ showLeafIcon: false }}
        // 使用titleRender进行自定义渲染
        titleRender={(nodeData) => renderTreeNode(nodeData)}
      />
    </div>
  );
};

export default OrgTree;
